# -*- coding: utf-8 -*-
# @Author: Turbidsoul
# @Date:   2017-05-20 16:56:04
# @Last Modified by:   Turbidsoul
# @Last Modified time: 2017-06-01 00:41:46


from urllib.parse import urlencode

import requests
from requests.cookies import RequestsCookieJar

_base = 'https://www.dida365.com'
_signon = _base + '/api/v2/user/signon'
_projects = _base + '/api/v2/projects'
_bind_events = _base + '/api/v2/calendar/bind/events'
_subscribe_events = _base + '/api/v2/calendar/subscribe/events'
_plugin_settings = _base + '/api/v2/user/preferences/pluginSettings'
_attachment_isunderquota = _base + '/api/v2/attachment/isUnderQuota'


class TokenError(Exception):
  pass


class Account(object):
  """用户信息"""
  __shots__ = ('token', 'userId', 'userCode', 'username', 'proEndDate',
               'subscribeType', 'subscribeFreq', 'needSubscribe', 'inboxId',
               'pro', 'json')
  def __init__(self, **kwargs):
    super(Account, self).__init__()
    self.__dict__.update(kwargs)
    self.json = kwargs


class Project(object):
  """清单"""
  __shots__ = ('id', 'name', 'isOwner', 'color', 'inAll', 'sortOrder',
               'sortType', 'userCount', 'etag', 'modifiedTime', 'closed',
               'groupId', 'json')
  def __init__(self, **kwargs):
    super(Project, self).__init__()
    self.__dict__.update(kwargs)
    self.json = kwargs
    

class BindEvent(object):
  """Calendar bind event"""
  __shots__ = ('id', 'name', 'events', 'json')
  def __init__(self, **kwargs):
    super(BindEvent, self).__init__()
    self.__dict__.update(kwargs)
    self.json = kwargs


class SubscribeEvent(object):
  """Calendar subscribe event"""
  __shots__ = ()
  def __init__(self, **kwargs):
    super(SubscribeEvent, self).__init__()
    self.__dict__.update(kwargs)
    self.json = kwargs
    
class PluginSetting(object):
  """PLugin"""
  __shots__ = ('enabled', 'id', 'name')
  def __init__(self, **kwargs):
    super(PluginSetting, self).__init__()
    self.__dict__.update(kwargs)
    self.name = self.id[7:]
            
    
class DidaV2(object):
  """
  嘀嗒365 V2 api

  """
  def __init__(self):
    super(DidaV2, self).__init__()
    self._account = None
    self._projects = []
    self._bind_events = []
    self._pluginsettings = []
    self._isUnderQuota = False

  @property
  def account(self):
    return self._account

  @property
  def token(self):
    return self._account.token

  @property
  def projects(self):
    return self._projects

  @property
  def bindEvents(self):
    return self._bindEvents

  @property
  def pluginSettings(self):
    return self._pluginSettings

  @property
  def isUnderQuota(self):
    return self._isUnderQuota
  
  
  def signon(self, username, password, wc=True, remember=True):
    """
    Function: signon
    Summary: 登陆接口，获取用户的登陆接口，获取用户的token和用户信息
    Examples:
    from dida365.api import DidaV2
    v2 = DidaV2()
    account = v2.signno('<username>', '<password>')
    print(account.token)
    Attributes: 
      @param (username):用户名
      @param (password):密码
      @param (wc) default=True: 
      @param (remember) default=True: 是否记住登陆状态
    Returns: Account

    """
    json = {
      'username': username,
      'password': password
    }
    params = {
      'wc': wc,
      'remember': remember
    }
    qs = urlencode(params)
    response = requests.post(_signon + "?" + qs, json=json)
    response.raise_for_status()
    assert 'userId' in response.json(), 'account[userId] None'
    self._account = Account(**(response.json()))
    return self._account
  
  def _gen_cookie(self):
    jar = RequestsCookieJar()
    jar.set('t', self.token)
    return jar

  def raise_for_verify(self):
    if not self.token:
      raise TokenError('token is fail')


  def fetch_projects(self):
    self.raise_for_verify()

    response = requests.get(_projects, cookies=self._gen_cookie())
    response.raise_for_status()
    for p in response.json():
      self._projects.append(Project(**p))
    return self._projects


  def fetch_bind_events(self):
    self.raise_for_verify()

    response = requests.get(_bind_events, cookies=self._gen_cookie())
    response.raise_for_status()
    for e in response.json():
      self._bind_events.append(BindEvent(**e))
    return self._bind_events

  def fetch_pluginsettings(self):
    self.raise_for_verify()

    response = requests.get(_plugin_settings, cookies=self._gen_cookie())
    response.raise_for_status()
    for p in response.json():
      self._pluginsettings.append(PluginSetting(**p))
    return self._pluginsettings

  def fetch_attachment_isunderquota(self):
    self.raise_for_verify()
    response = requests.get(_attachment_isunderquota, cookies=self._gen_cookie())
    response.raise_for_status()
    self._isUnderQuota = bool(response.text())
    return self._isUnderQuota
